package com.android.lovely.ui.dialog

import androidx.fragment.app.activityViewModels
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.android.lovely.databinding.DialogChatEditBinding
import com.android.lovely.ext.MessageHelper.applyMessageWithStyle
import com.android.lovely.ext.MessageHelper.roleStyle
import com.android.lovely.framework.BaseDialogFragment
import com.android.lovely.room.chat.database.ReceivedTextMessage
import com.android.lovely.ui.chat.ConversationViewModel
import com.android.lovely.ui.chat.getChatId
import com.kotlin.extensions.keyboard.showKeyboard
import com.kotlin.extensions.view.ViewExt.clickable

/**
 *
 * @author why
 * @date 2025/3/28 14:44
 */
class MessageEditDialog : BaseDialogFragment<DialogChatEditBinding>() {
    private val viewModel by activityViewModels<ConversationViewModel> {
        viewModelFactory {
            initializer {
                ConversationViewModel(getChatId())
            }
        }
    }

    override fun initializeViews() {
        binding.content.post {
            binding.content.showKeyboard()
        }
        binding.cancel.clickable { dismiss() }
        val message = arguments?.getParcelable("message") as? ReceivedTextMessage ?: return
        binding.content.setText(message.message.applyMessageWithStyle(roleStyle))
        binding.content.setSelection(binding.content.text?.length ?: 0)
        binding.confirm.clickable {
            if (binding.content.text.isNullOrBlank()) return@clickable
            viewModel.updateMessageContent(message, binding.content.text.toString())
            dismiss()
        }
    }

    override fun isBottom(): Boolean {
        return true
    }
}